<style>
    .drawer-footer {
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        border-top: 1px solid #e8e8e8;
        padding: 10px 16px;
        text-align: right;
        background: #fff;
    }
</style>
<template>
    <v-coreLayout ref="coreLayout" :step="3" :countdownTime="240">
        <template slot="content">
            <v-exception ref="exceptionModel"></v-exception>
            <Row style="height: 100%" type="flex">
                <Col span="24"
                     style="display:flex;justify-content:center;flex-direction:column;padding-left: 50px;padding-right: 50px;">
                    <Drawer title="高质量付费打印模式 · High Quality Mode (WeChat Pay)" :closable="true" v-model="payPrintModel"
                            :transfer="false"
                            :inner="true" width="600">
                        <div style="display:flex;flex-direction:column;align-items: center;margin: 10px;">
                            <div style="font-size: 18px;">
                                <p style="text-align:left;color:#f60;">超低价格 助力好成绩</p>
                                <p style="text-align:left">
                                    您选择的模式为
                                    <span style="color:#2b85e4">高质量付费打印</span>
                                    ，此模式下墨拓将采用
                                    <span style="color:#2b85e4">高质量模式[高等质量]</span>
                                    为您进行资料打印。当前价格为维持设备正常运维的成本价格，低于校内打印社30%以上。
                                </p>
                                <p style="text-align: center;margin-top: 25px">
                                    <span style="color:#2b85e4;">您应支付</span>
                                    <span style="font-size: 40px;">{{count}} x 0.10￥ = {{(count*0.1).toFixed(2)}}￥</span>
                                    <span style="color:#2b85e4;">打印成本</span>
                                </p>
                            </div>
                            <Divider/>
                            <div ref="wxPayQRCode"
                                 style="display: flex;justify-content: center;margin: 10px"></div>
                            <img src="../images/pay.png" width="150" padding="10px">
                            <h2 style="color:#2b85e4">请使用微信扫描上方二维码进行支付</h2>
                            <h3>Please use wechat to scan the QR code above for payment</h3>
                            <Spin fix v-if="loading_QR">
                                <Icon type="ios-loading" size=50 class="spin-icon-load"></Icon>
                                <div>正在计算打印费用中</div>
                                <div>网络可能存在延迟，请稍等</div>
                            </Spin>
                        </div>
                        <div class="drawer-footer">
                            <Button type="success" size="large" icon="md-checkmark-circle-outline"
                                    :loading="printLoading" @click="payPrintConfirm">我已完成支付 / Already Pay
                            </Button>
                            <Button type="warning" size="large" icon="md-close" @click="closeAllModel">取消 / Cancel
                            </Button>
                        </div>
                    </Drawer>
                    <Drawer title="打印卡券 免费高质量打印 · High Quality Mode (FREE CARD PAY)" :closable="true"
                            v-model="redeemCodePayModel" :transfer="false"
                            :inner="true" width="800">
                        <div style="display:flex;flex-direction:column;align-items: center;">
                            <img src="../images/discount_coupon.png" width="80" style="margin: 20px;">
                            <h2>请输入您卡片的兑换CDKEY</h2>
                            <h3>Please enter your card's exchange CDKEY</h3>
                            <p style="margin: 20px;font-size: 16px;">
                                <Icon type="ios-alert-outline"/>
                                本卡为计页付费类型卡，剩余张数不足时不可打印，请在输入兑换码后点击核对按钮进行查询核对。
                            </p>
                            <Input v-model="redeemCode" size="large" placeholder="请输入八位兑换码 / Your CDKEY"
                                   style="width: 400px;">
                                <Button slot="append" icon="ios-search" @click="checkCardVaild">核对 / Check</Button>
                            </Input>
                            <p style="margin: 10px;color: #2b85e4">{{cardInfo}}</p>
                            <v-keyboard v-on:updatekey="getRedeemCode"></v-keyboard>
                            <div class="drawer-footer">
                                <Button type="success" size="large" icon="md-checkmark-circle-outline"
                                        :loading="printLoading" @click="cardPrintConfirm">确认 / Confirm
                                </Button>
                                <Button type="warning" size="large" icon="md-close" @click="closeAllModel">取消 / Cancel
                                </Button>
                            </div>
                        </div>
                    </Drawer>
                    <div style="display:flex;align-items:center;flex-direction:column;justify-content:center">
                        <div style="display:flex;align-items:center;justify-content:center;margin-bottom: 20px;">
                            <img src="../images/ADPrinting.png" height="250" style="margin-right: 40px;">
                            <div style="font-size: 20px">
                                <h3 style="text-align:left;">助力环保 公益打印</h3>
                                <Divider/>
                                <p style="text-align:left">
                                    您选择的模式为
                                    <span style="color:#2b85e4">免费打印</span>
                                    ，此模式下墨拓将采用
                                    <span style="color:#2b85e4">环保模式[中等质量]</span>
                                    为您进行资料打印。注意，墨拓将仅在
                                    <span style="color:#d68146">不覆盖页面内容的页边距位置</span>
                                    处进行广告印制，
                                    <span style="color:#d68146">广告内容为校招企业文化故事、行业人才需求概况、公益广告等。</span>
                                    墨拓承诺，每笔打印业务所产生效益，将向公益组织捐献 15% 用于留守儿童关爱、乡村知识扶贫、重症儿童救助等方面。同时，墨拓将以不低于 30%
                                    的比例投放免费纯公益性广告、宣传视频等内容。
                                </p>
                            </div>
                        </div>
                        <p style="text-align: left;font-size: 16px ;margin-top: 10px;color: #808695">
                            <Icon type="ios-alert-outline"/>
                            点墨对通过自助设备投放广告的企业已尽到包括资质审查、广告真实性核验在内的必要保真义务，但对于任何包含于、经由或从任何与点墨有关服务所获得的信息、内容或广告，不声明或保证其正确性或可靠性。您于此接受并承认信赖任何信息、内容或广告所发生的风险都应自行承担，对于因此所生的任何直接、间接、附带的或因此而导致的衍生性损失概不负责。
                        </p>

                        <div style="display:flex;justify-content:flex-end;width: 100%">
                            <Button @click="freePrintConfirm" type="success" size="large" :loading="printLoading"
                                    icon="md-print"
                                    style="width: 340px;margin-top: 20px;height: 45px;">
                                <p style="font-size: 18px;">确认 / Confirm</p>
                            </Button>
                        </div>

                        <!-- <Divider>或</Divider> -->


                        <!-- <div> -->
                            <!-- <Button @click="payPrint" type="primary" size="large" icon="md-chatbubbles"
                                    style="width: 340px;margin-bottom: 10px;height: 50px;margin-right: 20px;" disabled>
                                <p style="font-size: 18px;">付费高质量打印 / 暂不支持</p>
                            </Button> -->
                            <!-- <Button @click="cardPrint" type="primary" size="large" icon="md-card"
                                    style="width: 340px;margin-bottom: 10px;height: 50px;" >
                                <p style="font-size: 18px;">兑换券打印 / HQ Mode (Card)</p>
                            </Button>
                        </div>
                        <p style="font-size: 18px;color: #2d8cf0">0.1 元/张（双面）超低成本价格，最高打印质量，不含任何类型广告</p> -->
                    </div>
                </Col>
            </Row>
        </template>
    </v-coreLayout>
</template>
<script>
    import * as axios from "axios";
    import ExceptionModel from '../components/ExceptionModel.vue';
    import CountdownButton from '../components/CountdownButton.vue';
    import Keyboard from '../components/Keyboard.vue';
    import CoreLayout from '../components/CoreLayout.vue';
    import QRCode from 'qrcodejs2';

    export default {
        components: {
            'v-exception': ExceptionModel,
            'v-countdownButton': CountdownButton,
            'v-keyboard': Keyboard,
            'v-coreLayout': CoreLayout,
        },
        data() {
            return {
                freePrintModel: false,
                payPrintModel: false,
                redeemCodePayModel: false,
                printLoading: false,
                loading_QR: false,
                defeatNum: 0,
                count: 0,
                initPayInfo: true,
                redeemCode: "",
                cardInfo: "",
            }
        },
        methods: {
            countdownReset() {
                this.$refs.countdown.countdownReset(300);
            },
            freePrint() {
                this.freePrintModel = true;
            },
            cardPrint() {
                this.redeemCodePayModel = true;
            },
            payPrint() {
                this.payPrintModel = true;
                if (this.initPayInfo) {
                    console.log("initQRCode");
                    this.initPayInfo = false;
                    this.getCount();
                    this.initWebSocket();
                }
            },
            closeAllModel() {
                this.freePrintModel = false;
                this.payPrintModel = false;
                this.redeemCodePayModel = false;
            },
            freePrintConfirm() {
                this.printLoading = true;
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/adAdd',
                    params: {
                        printUserMark: this.$root.printUserMark,
                    }
                }).then((response) => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        this.printLoading = false;
                        this.freePrintModel = false;
                        this.$Message.success('开始打印');
                        this.$router.push({
                            name: 'Print',
                            params: {
                                printMode: 1,
                            }
                        });
                    } else {
                        this.closeAllModel();
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            cardPrintConfirm() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/requestServerData/payment/doUseCardToPay',
                    params: {
                        cdkey: this.redeemCode,
                        count: this.count,
                    }
                }).then((response) => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        this.printLoading = false;
                        this.freePrintModel = false;
                        this.$Message.success('开始打印');
                        this.$router.push({
                            name: 'Print',
                            params: {
                                printMode: 3,
                            }
                        });
                    } else {
                        this.$Modal.confirm({
                            title: '支付未成功',
                            content: '您的卡片已经失效或余额不足，如有疑问请联系墨拓官方处理。',
                            okText: '确认',
                            onOk: () => {
                                this.$Modal.remove();
                            },
                        });
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            payPrintConfirm() {
                this.printLoading = true;
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/requestServerData/payment/checkPrinterOrderState',
                    params: {
                        printUserMark: this.$root.printUserMark,
                    }
                }).then((response) => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        this.printLoading = false;
                        this.freePrintModel = false;
                        this.$Message.success('开始打印');
                        this.$router.push({
                            name: 'Print',
                            params: {
                                printMode: 2,
                            }
                        });
                    } else {
                        this.$Modal.confirm({
                            title: '支付未成功',
                            content: '若您确认已经完成支付，请拍摄用户唯一编码' + this.$root.printUserMark + '至微信公众号办理自助退款手续，给您带来不便我们深表歉意。',
                            okText: '确认',
                            onOk: () => {
                                this.$Modal.remove();
                            },
                        });
                        this.printLoading = false;
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            getCount() {
                this.loading_QR = true;
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/getPaperConsumedNum',
                    params: {
                        printUserMark: this.$root.printUserMark,
                    }
                }).then(response => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        this.count = responseData.msg
                        this.getQRCodePic();
                    } else {
                        this.closeAllModel();
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            getQRCodePic() {
                //[控制端指令]请求服务器端二维码
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/requestServerData/payment/newPrinterOrder',
                    params: {
                        count: this.count,
                        printUserMark: this.$root.printUserMark,
                    }
                }).then(response => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        new QRCode(this.$refs.wxPayQRCode, {
                            text: responseData.msg,
                            width: 130,
                            height: 130,
                            colorDark: "#333333", //二维码颜色
                            colorLight: "#ffffff", //二维码背景色
                            correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
                        })
                        this.loading_QR = false;
                    } else {
                        this.closeAllModel();
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            checkCardVaild() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/requestServerData/payment/getCardInfoByCDKey',
                    params: {
                        cdkey: this.redeemCode,
                    }
                }).then(response => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        let isValid = (responseData.msg.isValid == 1) ? "正常" : "作废"
                        this.cardInfo = "券类型：计次消费 剩余打印数量：" + responseData.msg.residueDegree + " 有效期至：" + responseData.msg.failureTime + " 当前状态：" + isValid;

                    } else {
                        this.cardInfo = "CDKEY不存在，请检查您的输入";
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            getRedeemCode(val) {
                this.redeemCode = val;
            },
            initWebSocket() { //初始化weosocket
                const url = this.$root.websocketUrl + 'webSocket/' + this.$root.printUserMark;
                this.websock = new WebSocket(url);
                this.websock.onmessage = this.websocketOnMessage;
                this.websock.onopen = this.websocketOnOpen;
                this.websock.onerror = this.websocketOnError;
                this.websock.onclose = this.websocketClose;
            },
            websocketOnOpen() {
                console.log("Successful establishment of WebSocket connection");
            },
            websocketOnError(e) {//连接建立失败重连并返回
                this.defeatNum++;
                console.log("Failure to establish WebSocket connection,The reasons for the error are as follows:");
                console.log(e);
                if (this.defeatNum < 6) {
                    var that = this;
                    if (e.type == "error") {
                        this.$Notice.error({
                            title: '与服务器建立WEBSOCKET通讯失败',
                            desc: '服务器未能响应请求，正在尝试重新连接 (第 ' + this.defeatNum + ' 次 / 共 5 次)，若依然失败，请联系MOTA官方 133-0535-6699 尝试解决此问题！',
                        });
                    }
                    setTimeout(function () {
                        that.initWebSocket()
                    }, 5 * 1000);
                } else {
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, "Error: WebSocket连接没有正确建立");
                }
            },
            websocketOnMessage(sendback) {//接收到服务器消息后
                var data = JSON.parse(sendback.data);
                if (data.state == 'SUCCESS' && data.code == '1') {
                    this.printLoading = false;
                    this.freePrintModel = false;
                    this.$Message.success('开始打印');
                    this.$router.push({
                        name: 'Print',
                        params: {
                            printMode: 2,
                        }
                    });
                }
            },
            websocketSend(data) {//数据发送
                this.websock.send(data)
            },
            websocketClose(e) {  //关闭
                this.websock.close()
                console.log('WebSocket Connection Disconnected', e)
            },
        },
    }
</script>